package cn.tedu.com.control;

import cn.tedu.com.bean.UserInfo;
import cn.tedu.com.exception.BusinessException;
import cn.tedu.com.service.IQuertUserInfo;
import cn.tedu.com.util.AppUtil;
import cn.tedu.com.util.ConstantUtil;
import cn.tedu.com.util.RedisPoolListenerUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/user")
public class LoginControl {
    @Autowired
    private IQuertUserInfo queryUserInfoImpl;
//    @Autowired
//    @Qualifier("srtOne")
//    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/login")
    @ResponseBody
    public UserInfo login(@RequestBody UserInfo userInfo,
                          HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            String name = cookie.getName();
            if(AppUtil.TOKEN.matches(name)){
                String value = cookie.getValue();
                String s = RedisPoolListenerUtil.getSRTDbByKey(RedisPoolListenerUtil.REDIS_STR_DB0).opsForValue().get(value);
                UserInfo userInfo1 = JSONObject.parseObject(s, UserInfo.class);
                return userInfo1;
            }
        }
        UserInfo userInfo1 = queryUserInfoImpl.selectLogin(userInfo);
        if(Objects.isNull(userInfo1)){
            throw new BusinessException("未查询到用户信息");
        }
        String uuidToken = UUID.randomUUID().toString();
        String userStr = JSON.toJSONString(userInfo1);
        RedisPoolListenerUtil.getSRTDbByKey(RedisPoolListenerUtil.REDIS_STR_DB0).opsForValue().setIfAbsent(uuidToken,userStr, ConstantUtil.TOKEN_TIME, TimeUnit.SECONDS);
        AppUtil.addUserInfo(userInfo);
        AppUtil.addToken(uuidToken);
        Cookie cookie=new Cookie(AppUtil.TOKEN,uuidToken);
        response.addCookie(cookie);
        return userInfo1;
    }
}
